package org.example.user.statistic.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.example.commons.config.MiniProgramUserProperties;
import org.example.commons.constant.Constants;
import org.example.commons.entity.SysUser;
import org.example.commons.utils.RedisCache;
import org.example.commons.vo.ResultVO;
import org.example.user.manage.qrcode.QrCodeUtils;
import org.example.user.manage.service.ISysUserService;
import org.example.user.manage.dto.SysHealthStatusDTO;
import org.example.user.manage.service.ISysHealthStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 处理微信小程序的二维码
 *
 * @author bothin
 */
@RestController
@RequestMapping("/api/qrcode")
public class QRCodeController {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysHealthStatusService healthStatusService;

    @Autowired
    private MiniProgramUserProperties miniProgramUserProperties;


    @Value("${bothin.weixin.qr-code-expireTime}")
    private int expireTime;

    /**
     * 小程序端的通行二维码
     */
    @GetMapping("/image/{key}")
    public void getQRCode(@PathVariable(name = "key") String key,
                          HttpServletResponse response) {
        String userId =  redisCache.getCacheObject(Constants.WX_QR_CODE_KEY + key);

            try {
                OutputStream os = response.getOutputStream();
                if (userId != null){
                    //把redis的key写进二维码
                    QrCodeUtils.encode(key, "/static/dgut.jpg", os, true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

    @GetMapping("/key")
    public ResultVO getQRCodeKey(@RequestParam(name = "userId") Long userId) throws JsonProcessingException {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("date", new Date());
        String json = new ObjectMapper().writeValueAsString(map);
        String key = DigestUtils.md5Hex(json);
        redisCache.setCacheObject(Constants.WX_QR_CODE_KEY + key, userId + "", expireTime, TimeUnit.MINUTES);
        ResultVO success = ResultVO.success();
        success.put("key",key);
        return success;
    }

    /**
     * 根据二维码中的key获取信息
     *
     * @param key redis中的key
     */
    @RequestMapping("/analysis")
    public ResultVO analysisQRCode(@RequestParam(name = "key", defaultValue = "") String key) {
        String userId = redisCache.getCacheObject(Constants.WX_QR_CODE_KEY + key);

        if (userId == null)
            return ResultVO.error("二维码已经失效！！");
        Long userId_L = Long.valueOf(userId);
        SysHealthStatusDTO healthStatusDTO = healthStatusService.findByUserIdDTO(userId_L);
        if (Objects.isNull(healthStatusDTO)) {
            return ResultVO.error("找不到该住户信息！！");
        }
        return ResultVO.success(healthStatusDTO);
    }

}
